"""
    @Author  ：思念 
    @File    ：3.协程环境中执行同步爬虫库.py
    @Date    ：2025/3/17 14:43 
"""
# requests是一个同步的库，所以不能在协程环境中使用，需要使用aiohttp
import requests
import asyncio

async def get_image(url):
    print(f'正在下载 {url}')
    future = loop.run_in_executor(None, requests.get, url)
    res = await future
    filename = url.split('/')[-1]
    with open(filename, 'wb') as f:
        f.write(res.content)
        print(f'{url} 下载完成')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    url_list = [
        'https://i0.hdslb.com/bfs/new_dyn/f5bf5520071bbc18c90bb30b718b3416275879870.jpg',
        'https://q3.itc.cn/q_70/images03/20250105/38455e7bf323474da8678127a1394da9.jpeg',
        'https://iknow-pic.cdn.bcebos.com/0b46f21fbe096b639e4aa7ce1e338744eaf8acd9'
    ]
    tasks = [loop.create_task(get_image(url)) for url in url_list]
    loop.run_until_complete(asyncio.wait(tasks))



"""
    若一个三方库必须要运行在协程环境中，则可以是用run_in_executor在协程环境中运行
    本质还是线程执行
"""